package com.bw.module_video_detail

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.bw.lib_common.base.BaseMVIActivity
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbus.LiveDataEventBus
import com.bw.lib_common.websocket.WebSocketUtils
import com.bw.lib_storage.UserMMKV
import com.bw.lib_storage.manager.PlayHistoryManager
import com.bw.module_video_detail.databinding.ActivityVideoDetailBinding
import com.bw.module_video_detail.mvi.intent.VideoDetailIntent
import com.bw.module_video_detail.mvi.model.entity.DanMuEntity
import com.bw.module_video_detail.mvi.state.BulletScreenState
import com.bw.module_video_detail.mvi.state.ModifyCoinAmountState
import com.bw.module_video_detail.mvi.state.PublishBulletScreenState
import com.bw.module_video_detail.mvi.viewmodel.VideoDetailViewModel
import com.bw.module_video_detail.widget.DanMuBottomSheetDialog
import com.bw.module_video_detail.widget.MyCacheStuffer
import com.bw.module_video_detail.widget.RedPacketEnum
import com.bw.module_video_detail.widget.RedPacketEvent
import com.bw.module_video_detail.widget.RedPacketView
import com.bw.module_video_detail.widget.RedPacketWidget
import com.google.gson.Gson
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.shuyu.gsyvideoplayer.player.IPlayerManager
import com.shuyu.gsyvideoplayer.render.GSYRenderView
import com.shuyu.gsyvideoplayer.render.view.IGSYRenderView
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import org.greenrobot.eventbus.EventBus
import org.java_websocket.handshake.ServerHandshake
import java.util.Random

@AndroidEntryPoint
class VideoDetailActivity : BaseMVIActivity(){
//    @Autowired
    var dataType:Int = 0 //视频类型
//    @Autowired
    var itemId:String = "6936590061114753549" //视频itemId
    private lateinit var mViewModel: VideoDetailViewModel
    private  val mBinding:ActivityVideoDetailBinding by lazy {
        ActivityVideoDetailBinding.inflate(layoutInflater)
    }

    private lateinit var dmContext:DanmakuContext //弹幕上下文
    private val dmParser:BaseDanmakuParser = object :BaseDanmakuParser(){ //弹幕解析器
        override fun parse(): IDanmakus {
            return Danmakus()
        }
    }

    private lateinit var webSocketUtils: WebSocketUtils
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[VideoDetailViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return mBinding.root
    }

    /**
     * mvi：根据状态处理ui
     */
    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.bulletScreenState_.collect{
                    when(it){
                        is BulletScreenState.Success -> {
                            //弹幕数据
                            for (entity in it.data){
                                addDanMu(entity)
                            }
                        }
                        is BulletScreenState.Error -> {
                            //弹幕数据错误
                        }
                        is BulletScreenState.Loading -> {

                        }
                        is BulletScreenState.Empty -> {
                            //弹幕数据为空
                        }
                        is BulletScreenState.Init -> {

                        }
                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.publishBulletScreenState_.collect{
                    when(it){
                        is PublishBulletScreenState.Success -> {
                            //弹幕发送成功
                            showMsg("弹幕发送成功")
                        }
                        is PublishBulletScreenState.Error -> {
                            //弹幕发送
                        }
                        is PublishBulletScreenState.Init -> {

                        }
                        is PublishBulletScreenState.Loading -> {

                        }

                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.modifyCoinAmountState_.collect{
                    when(it){
                        is ModifyCoinAmountState.Success -> {
                            //红包发送成功
                            showMsg("金币修改成功")
                            //发送全局事件总线
                            LiveDataEventBus.postEvent(Events.EVENT_RED_PACKET,true)
                        }
                        is ModifyCoinAmountState.Error -> {
                            //红包发送失败
                        }
                        is ModifyCoinAmountState.Init -> {

                        }
                    }
                }
            }
        }

    }

    override fun initView() {
        super.initView()
        initGSY()
        initDanMu()
        initWebsocket() //初始化websocket
        mBinding.rpvHomeDetailRedpacket.setNum(100)
    }

    private fun initWebsocket() {
        webSocketUtils = WebSocketUtils.Builder()
            .setUri("ws://10.161.9.80:7037/api/danmu/websocket/$itemId")
            .setReceiveMessageListener(object : WebSocketUtils.ReceiveMessageListener{
                override fun onMessage(message: String?) {
                    //接收到弹幕信息
                    showMsg("接收到弹幕信息"+message)
                    //过滤掉心跳
                    if (message?.contains("heartbeat") == false){
                        val entity = Gson().fromJson<DanMuEntity>(message, DanMuEntity::class.java)
                        addDanMu(entity)
                    }

                }

                override fun onOpen(shake: ServerHandshake?) {
                    showMsg("打开链接")

                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    showMsg("关闭链接")

                }

                override fun onError(ex: Exception?) {
                    showMsg("链接失败"+ex?.message)

                }

            }).build()
    }

    /**
     * 初始化视频播放器
     */
    private fun initGSY() {
        // 初始化播放历史管理器
        PlayHistoryManager.init(this)
        lifecycleScope.launch {
            val historyList = PlayHistoryManager.getAllHistory()
            Log.d("PlayHistory", "onClick: "+historyList)
        }
        
        mBinding.gsyHomeDetail.setUpLazy("http://txmov2.a.yximgs.com/upic/2020/08/23/20/BMjAyMDA4MjMyMDU3MzVfNDc1MTQ4NzZfMzQ4NzcwMzIxOTlfMV8z_b_B09a31110bdc2b61828d27ef27390ecec.mp4?tag=1-1599270586-vdg-1-h2fj3f9rtd-6b0b801241e3b41e&tt=b&bp=10000",true,null,null,"")
        mBinding.gsyHomeDetail.titleTextView.visibility=View.GONE
        mBinding.gsyHomeDetail.backButton.visibility=View.GONE
        mBinding.gsyHomeDetail.fullscreenButton.setOnClickListener {
            mBinding.gsyHomeDetail.startWindowFullscreen(this@VideoDetailActivity,false,true)
        }
        mBinding.gsyHomeDetail.isShowFullAnimation=true
        
        // 恢复播放进度
        restorePlayProgress()
        
        //自动播放
        mBinding.gsyHomeDetail.startButton.performClick()

        // 设置播放进度监听器
        mBinding.gsyHomeDetail.setGSYVideoProgressListener(object : GSYVideoProgressListener {
            override fun onProgress(p0: Long, p1: Long, p2: Long, p3: Long) {
                // 更新播放进度
                updatePlayProgress(p2.toLong(), p3.toLong())
            }

        })

        //控制弹幕的绘制
        mBinding.gsyHomeDetail.setVideoAllCallBack(object : GSYSampleCallBack(){
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                // 视频准备完成，记录开始播放
                recordPlayStart()
            }
            
            override fun onAutoComplete(url: String?, vararg objects: Any?) {
                super.onAutoComplete(url, *objects)
                // 播放完成
                recordPlayComplete()
            }
            
            override fun onClickResume(url: String?, vararg objects: Any?) {
                super.onClickResume(url, *objects)
                EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME)) //继续红包
                dmResume()
            }

            override fun onClickStop(url: String?, vararg objects: Any?) {
                super.onClickStop(url, *objects)
                EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))//暂停红包
                dmPause()
            }
        })
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT)) //初始化红包
    }

    override fun initEvent() {
        super.initEvent()
        //发送弹幕
        mBinding.tvHomeDetailDanmu.setOnClickListener {
            val bottom = DanMuBottomSheetDialog()
            bottom.setDanMuListener(object :DanMuBottomSheetDialog.DanMuListener{
                override fun onClick() {
                    //1:本地显示弹幕信息
                    val content = bottom.etContent?.text.toString()
                    if (content.isBlank()){
                        showMsg("弹幕不能为空")
                        return
                    }
                    val entity = DanMuEntity(content = content, fontsize = 40, fontcolor = "#ff0000", datatype = dataType, itemid = itemId)
                    addDanMu(entity)
                    //2：调用接口发送弹幕
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.RESUMED){
                            entity.playtime_ =  mBinding.gsyHomeDetail.currentPositionWhenPlaying.toLong()//视频当前进度
                            mViewModel.intents.send(VideoDetailIntent.publishBulletScreen(entity))
                        }
                    }
                    bottom.close()

                }
            })
            bottom.show(supportFragmentManager)
        }
        //弹幕开关
        mBinding.switchHomeDetailBulletscreen.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                mBinding.danmakuView.restart()
            }else{
                mBinding.danmakuView.stop()
            }
        }
        //上报金币
        mBinding.rpvHomeDetailRedpacket.setStateCallBack(object : RedPacketWidget.StateCallBack{
            override fun completed() {
                if (UserMMKV.token.isNullOrEmpty()){
                    showMsg("请先登录")
                    return
                }
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.RESUMED){
                        mViewModel.intents.send(VideoDetailIntent.modifyCoinAmount(UserMMKV.accountId,100))
                    }
                }
            }

        })
    }

    override fun initData() {
        super.initData()
        //网络请求数据
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){ //页面活跃的时候处理流
                mViewModel.intents.send(VideoDetailIntent.getBulletScreenInfo(dataType,itemId))
            }
        }

    }

    /**
     * 初始化弹幕
     */
    private fun initDanMu() {
        //设置最大显示行数
        val max:HashMap<Int, Int> = HashMap()
        max[BaseDanmaku.TYPE_SCROLL_RL] = 8 //设置最大显示行数
        //设置是否禁止重叠
        val over:HashMap<Int,Boolean> = HashMap()
        over[BaseDanmaku.TYPE_SCROLL_RL] = true
        //创建弹幕上下文
        dmContext = DanmakuContext.create()
        //设置弹幕属性
        dmContext.setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
            .setCacheStuffer(MyCacheStuffer(this), object : BaseCacheStuffer.Proxy() {
                override fun prepareDrawing(p0: BaseDanmaku?, p1: Boolean) {

                }

                override fun releaseResource(p0: BaseDanmaku?) {
                    p0?.tag = null
                }

            }) //自定义渲染器
            .setMaximumLines(max) //最大行数
            .preventOverlapping(over) //防止重叠

        mBinding.danmakuView.setCallback(object : DrawHandler.Callback{
            override fun prepared() {
                //准备完成播放弹幕
                if (mBinding.switchHomeDetailBulletscreen.isChecked){//判断开关
                    mBinding.danmakuView.start()
                }

            }

            override fun updateTimer(p0: DanmakuTimer?) {

            }

            override fun danmakuShown(p0: BaseDanmaku?) {

            }

            override fun drawingFinished() {

            }
        })
        mBinding.danmakuView.prepare(dmParser,dmContext) //准备弹幕
        mBinding.danmakuView.enableDanmakuDrawingCache( true) //缓存弹幕

    }


    /**
     * 背景的颜色
     */
    private val mContentColorBg = arrayOf("#0099ff", "#b2d15c", "#b9b9f1", "#f46c77")
    /**
     * 添加弹幕信息
     */
    private fun addDanMu(entity: DanMuEntity){
        //创建一条弹幕
        val  danMu:BaseDanmaku = dmContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        //设置弹幕属性
//        if (entity.fontsize == 0){
//            danMu.textSize = 35f
//        }else{
//            danMu.textSize = entity.fontsize.toFloat() //字体大小
//        }
//        if(entity.fontcolor.isNullOrEmpty()){
//            danMu.textColor = Color.WHITE
//        }else{
//            danMu.textColor = Color.parseColor(entity.fontcolor) //字体颜色
//        }
//        danMu.text = entity.content //内容
        danMu.time = mBinding.danmakuView.currentTime + entity.playtime_
        //其他属性
        val bitmap:Bitmap = BitmapFactory.decodeResource(resources,R.drawable.home_danmu)
        val map = HashMap<String, Any>()
        map["bitmap"] = bitmap
        map["content"] = entity.content
        val random = Random()
        val index = random.nextInt(mContentColorBg.size)
        map["color"] = mContentColorBg[index] //背景颜色

        danMu.tag = map  //自定义渲染器传入的属性
        //添加弹幕
        mBinding.danmakuView.addDanmaku(danMu)
    }




    private fun dmPause(){
        //暂停弹幕绘制
        if (mBinding.danmakuView != null && mBinding.danmakuView.isPrepared){
            mBinding.danmakuView.pause()
        }
    }
    private fun dmResume(){
        //继续弹幕绘制
        if (mBinding.danmakuView != null && mBinding.danmakuView.isPrepared && mBinding.danmakuView.isPaused){
            mBinding.danmakuView.resume()
        }
    }



    override fun onPause() {
        super.onPause()
        dmPause()

    }

    override fun onResume() {
        super.onResume()
        dmResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放弹幕
        if (mBinding.danmakuView != null){
            mBinding.danmakuView.release()
        }
        //释放webSocket
        webSocketUtils.closeConnect()
        //释放红包资源
        mBinding.rpvHomeDetailRedpacket.release()
    }
    
    /**
     * 恢复播放进度
     */
    private fun restorePlayProgress() {
        lifecycleScope.launch {
            try {
                val history = PlayHistoryManager.getHistoryByVideoId(itemId)
                history?.let {
                    if (it.currentPosition > 0 && it.duration > 0) {
                        // 恢复播放进度
                        mBinding.gsyHomeDetail.seekTo(it.currentPosition.toLong())
                        Log.d("PlayHistory", "恢复播放进度: ${it.currentPosition}ms")
                    }
                }
            } catch (e: Exception) {
                Log.e("PlayHistory", "恢复播放进度失败", e)
            }
        }
    }
    
    /**
     * 记录开始播放
     */
    private fun recordPlayStart() {
        lifecycleScope.launch {
            try {
                PlayHistoryManager.addOrUpdateHistory(
                    videoId = itemId,
                    title = "测试视频标题 - $itemId", // 这里应该从视频数据中获取
                    coverUrl = "https://picsum.photos/300/200?random=$itemId", // 这里应该从视频数据中获取
                    videoUrl = "http://txmov2.a.yximgs.com/upic/2020/08/23/20/BMjAyMDA4MjMyMDU3MzVfNDc1MTQ4NzZfMzQ4NzcwMzIxOTlfMV8z_b_B09a31110bdc2b61828d27ef27390ecec.mp4?tag=1-1599270586-vdg-1-h2fj3f9rtd-6b0b801241e3b41e&tt=b&bp=10000",
                    currentPosition = 0,
                    duration = 0, // 从播放器获取
                    content = "这是一个测试视频的描述内容，用于演示播放历史记录功能。",
                    authorName = "测试作者",
                    userId = UserMMKV.userId ?: "test_user"
                )
                Log.d("PlayHistory", "记录播放开始")
            } catch (e: Exception) {
                Log.e("PlayHistory", "记录播放历史失败", e)
            }
        }
    }
    
    /**
     * 更新播放进度
     */
    private fun updatePlayProgress(currentPosition: Long, duration: Long) {
        lifecycleScope.launch {
            try {
                PlayHistoryManager.updatePlayProgress(itemId, currentPosition, duration)
            } catch (e: Exception) {
                Log.e("PlayHistory", "更新播放进度失败", e)
            }
        }
    }
    
    /**
     * 记录播放完成
     */
    private fun recordPlayComplete() {
        lifecycleScope.launch {
            try {
                // 播放完成，更新为已完成状态
                val history = PlayHistoryManager.getHistoryByVideoId(itemId)
                history?.let {
                    PlayHistoryManager.addOrUpdateHistory(
                        videoId = it.videoId,
                        title = it.title,
                        coverUrl = it.coverUrl,
                        videoUrl = it.videoUrl,
                        currentPosition = it.duration, // 设置为总时长
                        duration = it.duration,
                        content = it.content,
                        authorName = it.authorName,
                        userId = it.userId
                    )
                }
                Log.d("PlayHistory", "记录播放完成")
            } catch (e: Exception) {
                Log.e("PlayHistory", "记录播放完成失败", e)
            }
        }
    }

}